<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<meta name="keywords" content="Dubbo,Nacos,注册中心" />
	<meta name="description" content="Dubbo 融合 Nacos 成为注册中心" />
	<!-- 网页标签标题 -->
	<title>Dubbo 融合 Nacos 成为注册中心</title>
	<link rel="shortcut icon" href="https://img.alicdn.com/tfs/TB1hgJpHAPoK1RjSZKbXXX1IXXa-64-64.png"/>
	<link rel="stylesheet" href="/build/documentation.css" />
</head>
<body>
	<div id="root"><div class="documentation-page" data-reactroot="" data-reactid="1" data-react-checksum="-265798342"><header class="header-container header-container-normal" data-reactid="2"><div class="header-body" data-reactid="3"><a href="/zh-cn/index.html" data-reactid="4"><img class="logo" src="/img/nacos_colorful.png" data-reactid="5"/></a><div class="search search-normal" data-reactid="6"><span class="icon-search" data-reactid="7"></span></div><span class="language-switch language-switch-normal" data-reactid="8">En</span><div class="header-menu" data-reactid="9"><img class="header-menu-toggle" src="/img/menu_gray.png" data-reactid="10"/><ul data-reactid="11"><li class="menu-item menu-item-normal" data-reactid="12"><a href="/zh-cn/index.html" data-reactid="13">首页</a></li><li class="menu-item menu-item-normal menu-item-normal-active" data-reactid="14"><a href="/zh-cn/docs/what-is-nacos.html" data-reactid="15">文档</a></li><li class="menu-item menu-item-normal" data-reactid="16"><a href="/zh-cn/blog/index.html" data-reactid="17">博客</a></li><li class="menu-item menu-item-normal" data-reactid="18"><a href="/zh-cn/community/index.html" data-reactid="19">社区</a></li><li class="menu-item menu-item-normal" data-reactid="20"><a href="https://cn.aliyun.com/product/aliware/mse?spm=nacos-website.topbar.0.0.0" data-reactid="21">企业版Nacos</a><img class="menu-img" src="https://img.alicdn.com/tfs/TB1esl_m.T1gK0jSZFrXXcNCXXa-200-200.png" data-reactid="22"/></li><li class="menu-item menu-item-normal" data-reactid="23"><a href="https://job.alibaba.com/zhaopin/position_detail.htm?trace=qrcode_share&amp;positionCode=GP633620" data-reactid="24">招贤纳士</a><img class="menu-img" src="https://img.alicdn.com/tfs/TB1esl_m.T1gK0jSZFrXXcNCXXa-200-200.png" data-reactid="25"/></li><li class="menu-item menu-item-normal" data-reactid="26"><a href="http://console.nacos.io/nacos/index.html" data-reactid="27">控制台样例</a></li></ul></div></div></header><div class="bar" data-reactid="28"><div class="bar-body" data-reactid="29"><img src="/img/docs.png" class="front-img" data-reactid="30"/><div class="bar-title" data-reactid="31"><span data-reactid="32">Nacos 文档</span><div class="bone bone-light" data-reactid="33"></div></div><img src="/img/docs.png" class="back-img" data-reactid="34"/></div></div><section class="content-section" data-reactid="35"><div class="content-body" data-reactid="36"><div class="sidemenu" data-reactid="37"><div class="sidemenu-toggle" data-reactid="38"><img src="https://img.alicdn.com/tfs/TB1E6apXHGYBuNjy0FoXXciBFXa-200-200.png" data-reactid="39"/></div><ul data-reactid="40"><li class="menu-item menu-item-level-1" data-reactid="41"><span data-reactid="42">Nacos </span><ul data-reactid="43"><li style="height:180px;overflow:hidden;" class="menu-item menu-item-level-2" data-reactid="44"><span data-reactid="45"><!-- react-text: 46 -->Nacos是什么?<!-- /react-text --><img style="transform:rotate(0deg);" class="menu-toggle" src="/img/arrow_down.png" data-reactid="47"/></span><ul data-reactid="48"><li class="menu-item menu-item-level-3" data-reactid="49"><a href="/zh-cn/docs/what-is-nacos.html" target="_self" data-reactid="50">Nacos简介</a></li><li class="menu-item menu-item-level-3" data-reactid="51"><a href="/zh-cn/docs/concepts.html" target="_self" data-reactid="52">概念</a></li><li class="menu-item menu-item-level-3" data-reactid="53"><a href="/zh-cn/docs/architecture.html" target="_self" data-reactid="54">架构</a></li><li class="menu-item menu-item-level-3" data-reactid="55"><a href="/zh-cn/docs/feature-list.html" target="_self" data-reactid="56">功能和需求列表</a></li></ul></li><li style="height:324px;overflow:hidden;" class="menu-item menu-item-level-2" data-reactid="57"><span data-reactid="58"><!-- react-text: 59 -->快速开始<!-- /react-text --><img style="transform:rotate(0deg);" class="menu-toggle" src="/img/arrow_down.png" data-reactid="60"/></span><ul data-reactid="61"><li class="menu-item menu-item-level-3" data-reactid="62"><a href="/zh-cn/docs/quick-start.html" target="_self" data-reactid="63">Nacos</a></li><li class="menu-item menu-item-level-3" data-reactid="64"><a href="/zh-cn/docs/quick-start-spring.html" target="_self" data-reactid="65">Nacos Spring</a></li><li class="menu-item menu-item-level-3" data-reactid="66"><a href="/zh-cn/docs/quick-start-spring-boot.html" target="_self" data-reactid="67">Nacos Spring Boot</a></li><li class="menu-item menu-item-level-3" data-reactid="68"><a href="/zh-cn/docs/quick-start-spring-cloud.html" target="_self" data-reactid="69">Nacos Spring Cloud</a></li><li class="menu-item menu-item-level-3" data-reactid="70"><a href="/zh-cn/docs/quick-start-docker.html" target="_self" data-reactid="71">Nacos Docker</a></li><li class="menu-item menu-item-level-3" data-reactid="72"><a href="/zh-cn/docs/use-nacos-with-dubbo.html" target="_self" data-reactid="73">Nacos Dubbo</a></li><li class="menu-item menu-item-level-3" data-reactid="74"><a href="/zh-cn/docs/use-nacos-with-kubernetes.html" target="_self" data-reactid="75">Nacos k8s</a></li><li class="menu-item menu-item-level-3" data-reactid="76"><a href="/zh-cn/docs/nacos-sync.html" target="_self" data-reactid="77">Nacos Sync</a></li></ul></li><li style="height:252px;overflow:hidden;" class="menu-item menu-item-level-2" data-reactid="78"><span data-reactid="79"><!-- react-text: 80 -->用户指南<!-- /react-text --><img style="transform:rotate(0deg);" class="menu-toggle" src="/img/arrow_down.png" data-reactid="81"/></span><ul data-reactid="82"><li class="menu-item menu-item-level-3" data-reactid="83"><a href="/zh-cn/docs/sdk.html" target="_self" data-reactid="84">Java的SDK</a></li><li class="menu-item menu-item-level-3" data-reactid="85"><a href="/zh-cn/docs/other-language.html" target="_self" data-reactid="86">其他语言的SDK</a></li><li class="menu-item menu-item-level-3" data-reactid="87"><a href="/zh-cn/docs/open-api.html" target="_self" data-reactid="88">Open-API指南</a></li><li class="menu-item menu-item-level-3" data-reactid="89"><a href="/zh-cn/docs/nacos-spring.html" target="_self" data-reactid="90">Nacos Spring</a></li><li class="menu-item menu-item-level-3" data-reactid="91"><a href="/zh-cn/docs/system-configurations.html" target="_self" data-reactid="92">Nacos系统参数介绍</a></li><li class="menu-item menu-item-level-3" data-reactid="93"><a href="/zh-cn/docs/faq.html" target="_self" data-reactid="94">FAQ</a></li></ul></li><li style="height:36px;overflow:hidden;" class="menu-item menu-item-level-2" data-reactid="95"><span data-reactid="96"><!-- react-text: 97 -->运维指南<!-- /react-text --><img style="transform:rotate(-90deg);" class="menu-toggle" src="/img/arrow_down.png" data-reactid="98"/></span><ul data-reactid="99"><li class="menu-item menu-item-level-3" data-reactid="100"><a href="/zh-cn/docs/deployment.html" target="_self" data-reactid="101">部署手册</a></li><li class="menu-item menu-item-level-3" data-reactid="102"><a href="/zh-cn/docs/cluster-mode-quick-start.html" target="_self" data-reactid="103">集群部署说明</a></li><li class="menu-item menu-item-level-3" data-reactid="104"><a href="/zh-cn/docs/management-api.html" target="_self" data-reactid="105">运维API</a></li><li class="menu-item menu-item-level-3" data-reactid="106"><a href="/zh-cn/docs/console-guide.html" target="_self" data-reactid="107">控制台手册</a></li><li class="menu-item menu-item-level-3" data-reactid="108"><a href="/zh-cn/docs/monitor-guide.html" target="_self" data-reactid="109">监控手册</a></li><li class="menu-item menu-item-level-3" data-reactid="110"><a href="/zh-cn/docs/nacos-config-benchmark.html" target="_self" data-reactid="111">服务配置模块压测报告</a></li><li class="menu-item menu-item-level-3" data-reactid="112"><a href="/zh-cn/docs/nacos-naming-benchmark.html" target="_self" data-reactid="113">服务发现模块压测报告</a></li><li class="menu-item menu-item-level-3" data-reactid="114"><a href="/zh-cn/docs/nacos-sync-use.html" target="_self" data-reactid="115">其他环境迁移到Nacos</a></li></ul></li><li style="height:36px;overflow:hidden;" class="menu-item menu-item-level-2" data-reactid="116"><span data-reactid="117"><!-- react-text: 118 -->开源共建<!-- /react-text --><img style="transform:rotate(-90deg);" class="menu-toggle" src="/img/arrow_down.png" data-reactid="119"/></span><ul data-reactid="120"><li class="menu-item menu-item-level-3" data-reactid="121"><a href="/zh-cn/docs/contributing.html" target="_self" data-reactid="122">贡献源码</a></li><li class="menu-item menu-item-level-3" data-reactid="123"><a href="/zh-cn/docs/contributing-flow.html" target="_self" data-reactid="124">贡献流程</a></li><li class="menu-item menu-item-level-3" data-reactid="125"><a href="/zh-cn/docs/pull-request.html" target="_self" data-reactid="126">pull request模板</a></li><li class="menu-item menu-item-level-3" data-reactid="127"><a href="/zh-cn/docs/how-to-reporting-bugs.html" target="_self" data-reactid="128">如何提交问题报告</a></li></ul></li><li style="height:36px;overflow:hidden;" class="menu-item menu-item-level-2" data-reactid="129"><span data-reactid="130"><!-- react-text: 131 -->社区<!-- /react-text --><img style="transform:rotate(-90deg);" class="menu-toggle" src="/img/arrow_down.png" data-reactid="132"/></span><ul data-reactid="133"><li class="menu-item menu-item-level-3" data-reactid="134"><a href="/zh-cn/docs/community.html" target="_self" data-reactid="135">社区</a></li><li class="menu-item menu-item-level-3" data-reactid="136"><a href="/zh-cn/docs/nacos-dev.html" target="_self" data-reactid="137">开发团队</a></li></ul></li></ul></li></ul></div><div class="doc-content markdown-body" data-reactid="138"><h1>Dubbo 融合 Nacos 成为注册中心</h1>
<p>Nacos 作为 Dubbo 生态系统中重要的注册中心实现，本文将会介绍如何进行 Dubbo 对接 Nacos 注册中心的工作。</p>
<h2>预备工作</h2>
<p>请确保后台已经启动 Nacos 服务，可先行参考 <a href="https://nacos.io/en-us/docs/quick-start.html">Nacos 快速入门</a>。</p>
<h2>快速上手</h2>
<p>Dubbo 融合 Nacos 成为注册中心的操作步骤非常简单，大致步骤可分为“增加 Maven 依赖”以及“配置注册中心“。</p>
<h3>增加 Maven 依赖</h3>
<p>只需要依赖Dubbo客户端即可，关于推荐的使用版本，请参考Dubbo官方文档或者咨询Dubbo开发人员：</p>
<pre><code class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>

    ...

    <span class="hljs-comment">&lt;!-- Dubbo dependency --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.alibaba<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>dubbo<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>[latest version]<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    
    <span class="hljs-comment">&lt;!-- 使用Spring装配方式时可选: --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.alibaba.spring<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-context-support<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>[latest version]<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>

    ...
    
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>
</code></pre>
<h3>配置注册中心</h3>
<p>假设您 Dubbo 应用使用 Spring Framework 装配，将有两种配置方法可选，分别为：<a href="https://mercyblitz.github.io/2018/01/18/Dubbo-%E5%A4%96%E9%83%A8%E5%8C%96%E9%85%8D%E7%BD%AE/">Dubbo Spring 外部化配置</a>以及 Spring XML 配置文件以及，笔者强烈推荐前者。</p>
<h3>Dubbo Spring 外部化配置</h3>
<p>Dubbo Spring 外部化配置是由 Dubbo <code>2.5.8</code> 引入的新特性，可通过 Spring <code>Environment</code> 属性自动地生成并绑定 Dubbo 配置 Bean，实现配置简化，并且降低微服务开发门槛。</p>
<p>假设您 Dubbo 应用的使用 Zookeeper 作为注册中心，并且其服务器 IP 地址为：<code>10.20.153.10</code>，同时，该注册地址作为 Dubbo 外部化配置属性存储在 <code>dubbo-config.properties</code> 文件，如下所示：</p>
<pre><code class="language-properties">## application
dubbo.application.name = your-dubbo-application

## Zookeeper registry address
dubbo.registry.address = zookeeper://10.20.153.10:2181
...
</code></pre>
<p>假设您的 Nacos Server 同样运行在服务器 <code>10.20.153.10</code> 上，并使用默认 Nacos 服务端口 <code>8848</code>，您只需将 <code>dubbo.registry.address</code> 属性调整如下：</p>
<pre><code class="language-properties">## 其他属性保持不变

## Nacos registry address
dubbo.registry.address = nacos://10.20.153.10:8848
##如果要使用自己创建的命名空间可以使用下面2种方式
#dubbo.registry.address = nacos://10.20.153.10:8848?namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932
#dubbo.registry.parameters.namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932
...
</code></pre>
<p>随后，重启您的 Dubbo 应用，Dubbo 的服务提供和消费信息在 Nacos 控制台中可以显示：</p>
<p><img src="https://img.alicdn.com/tfs/TB1n6m7zMTqK1RjSZPhXXXfOFXa-2784-1058.png" alt="image-20181213103845976-4668726.png | left | 747x284"></p>
<p>如图所示，服务名前缀为 <code>providers:</code> 的信息为服务提供者的元信息，<code>consumers:</code> 则代表服务消费者的元信息。点击“<strong>详情</strong>”可查看服务状态详情：</p>
<p><img src="https://img.alicdn.com/tfs/TB1vZzfzQzoK1RjSZFlXXai4VXa-2714-1588.png" alt="image-20181213104145998-4668906.png | left | 747x437"></p>
<p>如果您正在使用 Spring XML 配置文件装配 Dubbo 注册中心的话，请参考下一节。</p>
<h3>Spring XML 配置文件</h3>
<p>同样，假设您 Dubbo 应用的使用 Zookeeper 作为注册中心，并且其服务器 IP 地址为：<code>10.20.153.10</code>，并且装配 Spring Bean 在 XML 文件中，如下所示：</p>
<pre><code class="language-xml"><span class="php"><span class="hljs-meta">&lt;?</span>xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"UTF-8"</span><span class="hljs-meta">?&gt;</span></span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans"</span>
    <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hljs-attr">xmlns:dubbo</span>=<span class="hljs-string">"http://dubbo.apache.org/schema/dubbo"</span>
    <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd        http://dubbo.apache.org/schema/dubbo        http://dubbo.apache.org/schema/dubbo/dubbo.xsd"</span>&gt;</span>
 
    <span class="hljs-comment">&lt;!-- 提供方应用信息，用于计算依赖关系 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:application</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dubbo-provider-xml-demo"</span>  /&gt;</span>
 
    <span class="hljs-comment">&lt;!-- 使用 Zookeeper 注册中心 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:registry</span> <span class="hljs-attr">address</span>=<span class="hljs-string">"zookeeper://10.20.153.10:2181"</span> /&gt;</span>
 	...
<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span>
</code></pre>
<p>与 <a href="https://mercyblitz.github.io/2018/01/18/Dubbo-%E5%A4%96%E9%83%A8%E5%8C%96%E9%85%8D%E7%BD%AE/">Dubbo Spring 外部化配置</a> 配置类似，只需要调整 <code>address</code> 属性配置即可：</p>
<pre><code class="language-xml"><span class="php"><span class="hljs-meta">&lt;?</span>xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"UTF-8"</span><span class="hljs-meta">?&gt;</span></span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans"</span>
    <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
    <span class="hljs-attr">xmlns:dubbo</span>=<span class="hljs-string">"http://dubbo.apache.org/schema/dubbo"</span>
    <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd        http://dubbo.apache.org/schema/dubbo        http://dubbo.apache.org/schema/dubbo/dubbo.xsd"</span>&gt;</span>
 
    <span class="hljs-comment">&lt;!-- 提供方应用信息，用于计算依赖关系 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:application</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dubbo-provider-xml-demo"</span>  /&gt;</span>
 
    <span class="hljs-comment">&lt;!-- 使用 Nacos 注册中心 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:registry</span> <span class="hljs-attr">address</span>=<span class="hljs-string">"nacos://10.20.153.10:8848"</span> /&gt;</span>
    <span class="hljs-comment">&lt;!-- 如果要使用自己创建的命名空间可以使用下面配置 --&gt;</span>
    <span class="hljs-comment">&lt;!-- &lt;dubbo:registry address="nacos://10.20.153.10:8848?namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932" /&gt; --&gt;</span>
 	...
<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span>
</code></pre>
<p>重启 Dubbo 应用后，您同样也能发现服务提供方和消费方的注册元信息呈现在 Nacos 控制台中：</p>
<p><img src="https://img.alicdn.com/tfs/TB1zl2dzQPoK1RjSZKbXXX1IXXa-2784-1022.png" alt="image-20181213113049185-4671849.png | left | 747x274"></p>
<p>您是否绝对配置或切换 Nacos 注册中心超级 Easy 呢？如果您仍旧意犹未尽或者不甚明白的话，可参考以下完整的示例。</p>
<h2>完整示例</h2>
<p>以上图片中的元数据源于 Dubbo Spring 注解驱动示例以及 Dubbo Spring XML 配置驱动示例，下面将分别介绍两者，您可以选择自己偏好的编程模型。在正式讨论之前，先来介绍两者的预备工作，因为它们皆依赖 Java 服务接口和实现。同时，<strong>请确保本地（<code>127.0.0.1</code>）环境已启动 Nacos 服务</strong>。</p>
<h3>示例接口与实现</h3>
<p>首先定义示例接口，如下所示：</p>
<pre><code class="language-java"><span class="hljs-keyword">package</span> com.alibaba.dubbo.demo.service;

<span class="hljs-comment">/**
 * DemoService
 *
 * <span class="hljs-doctag">@since</span> 2.6.5
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">DemoService</span> </span>{

    <span class="hljs-function">String <span class="hljs-title">sayName</span><span class="hljs-params">(String name)</span></span>;

}
</code></pre>
<p>提供以上接口的实现类：</p>
<pre><code class="language-java"><span class="hljs-keyword">package</span> com.alibaba.dubbo.demo.service;

<span class="hljs-keyword">import</span> com.alibaba.dubbo.config.annotation.Service;
<span class="hljs-keyword">import</span> com.alibaba.dubbo.rpc.RpcContext;

<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Value;

<span class="hljs-comment">/**
 * Default {<span class="hljs-doctag">@link</span> DemoService}
 *
 * <span class="hljs-doctag">@since</span> 2.6.5
 */</span>
<span class="hljs-meta">@Service</span>(version = <span class="hljs-string">"${demo.service.version}"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DefaultService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">DemoService</span> </span>{

    <span class="hljs-meta">@Value</span>(<span class="hljs-string">"${demo.service.name}"</span>)
    <span class="hljs-keyword">private</span> String serviceName;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">sayName</span><span class="hljs-params">(String name)</span> </span>{
        RpcContext rpcContext = RpcContext.getContext();
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"Service [name :%s , port : %d] %s(\"%s\") : Hello,%s"</span>,
                serviceName,
                rpcContext.getLocalPort(),
                rpcContext.getMethodName(),
                name,
                name);
    }
}
</code></pre>
<p>接口与实现准备妥当后，下面将采用注解驱动和 XML 配置驱动各自实现。</p>
<h3>Spring 注解驱动示例</h3>
<p>Dubbo <code>2.5.7</code> 重构了 Spring 注解驱动的编程模型。</p>
<h4>服务提供方注解驱动实现</h4>
<ul>
<li>定义 Dubbo 提供方外部化配置属性源 -  <code>provider-config.properties</code></li>
</ul>
<pre><code class="language-properties">## application
dubbo.application.name = dubbo-provider-demo

## Nacos registry address
dubbo.registry.address = nacos://127.0.0.1:8848
##如果要使用自己创建的命名空间可以使用下面2种方式
#dubbo.registry.address = nacos://127.0.0.1:8848?namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932
#dubbo.registry.parameters.namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932

## Dubbo Protocol
dubbo.protocol.name = dubbo
dubbo.protocol.port = -1

# Provider @Service version
demo.service.version=1.0.0
demo.service.name = demoService
</code></pre>
<ul>
<li>实现服务提供方引导类 - <code>DemoServiceProviderBootstrap</code></li>
</ul>
<pre><code class="language-java"><span class="hljs-keyword">package</span> com.alibaba.dubbo.demo.provider;

<span class="hljs-keyword">import</span> com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
<span class="hljs-keyword">import</span> com.alibaba.dubbo.demo.service.DemoService;

<span class="hljs-keyword">import</span> org.springframework.context.annotation.AnnotationConfigApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.PropertySource;

<span class="hljs-keyword">import</span> java.io.IOException;

<span class="hljs-comment">/**
 * {<span class="hljs-doctag">@link</span> DemoService} provider demo
 */</span>
<span class="hljs-meta">@EnableDubbo</span>(scanBasePackages = <span class="hljs-string">"com.alibaba.dubbo.demo.service"</span>)
<span class="hljs-meta">@PropertySource</span>(value = <span class="hljs-string">"classpath:/provider-config.properties"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DemoServiceProviderBootstrap</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException </span>{
        AnnotationConfigApplicationContext context = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext();
        context.register(DemoServiceProviderBootstrap.class);
        context.refresh();
        System.out.println(<span class="hljs-string">"DemoService provider is starting..."</span>);
        System.in.read();
    }
}

</code></pre>
<p>其中注解 <code>@EnableDubbo</code> 激活 Dubbo 注解驱动以及外部化配置，其 <code>scanBasePackages</code> 属性扫描指定 Java 包，将所有标注 <code>@Service</code> 的服务接口实现类暴露为 Spring Bean，随即被导出 Dubbo 服务。</p>
<p><code>@PropertySource</code> 是 Spring Framework 3.1 引入的标准导入属性配置资源注解，它将为 Dubbo 提供外部化配置。</p>
<h4>服务消费方注解驱动实现</h4>
<ul>
<li>定义 Dubbo 消费方外部化配置属性源 -  <code>consumer-config.properties</code></li>
</ul>
<pre><code class="language-properties">## Dubbo Application info
dubbo.application.name = dubbo-consumer-demo

## Nacos registry address
dubbo.registry.address = nacos://127.0.0.1:8848
##如果要使用自己创建的命名空间可以使用下面2种方式
#dubbo.registry.address = nacos://127.0.0.1:8848?namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932
#dubbo.registry.parameters.namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932

# @Reference version
demo.service.version= 1.0.0
</code></pre>
<p>同样地，<code>dubbo.registry.address</code> 属性指向 Nacos 注册中心，其他 Dubbo 服务相关的元信息通过 Nacos 注册中心获取。</p>
<ul>
<li>实现服务消费方引导类 - <code>DemoServiceConsumerBootstrap</code></li>
</ul>
<pre><code class="language-java"><span class="hljs-keyword">package</span> com.alibaba.dubbo.demo.consumer;

<span class="hljs-keyword">import</span> com.alibaba.dubbo.config.annotation.Reference;
<span class="hljs-keyword">import</span> com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
<span class="hljs-keyword">import</span> com.alibaba.dubbo.demo.service.DemoService;

<span class="hljs-keyword">import</span> org.springframework.context.annotation.AnnotationConfigApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.PropertySource;

<span class="hljs-keyword">import</span> javax.annotation.PostConstruct;
<span class="hljs-keyword">import</span> java.io.IOException;

<span class="hljs-comment">/**
 * {<span class="hljs-doctag">@link</span> DemoService} consumer demo
 */</span>
<span class="hljs-meta">@EnableDubbo</span>
<span class="hljs-meta">@PropertySource</span>(value = <span class="hljs-string">"classpath:/consumer-config.properties"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DemoServiceConsumerBootstrap</span> </span>{

    <span class="hljs-meta">@Reference</span>(version = <span class="hljs-string">"${demo.service.version}"</span>)
    <span class="hljs-keyword">private</span> DemoService demoService;

    <span class="hljs-meta">@PostConstruct</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
            System.out.println(demoService.sayName(<span class="hljs-string">"小马哥（mercyblitz）"</span>));
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException </span>{
        AnnotationConfigApplicationContext context = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext();
        context.register(DemoServiceConsumerBootstrap.class);
        context.refresh();
        context.close();
    }
}

</code></pre>
<p>同样地，<code>@EnableDubbo</code>  注解激活 Dubbo 注解驱动和外部化配置，不过当前属于服务消费者，无需指定 Java 包名扫描标注 <code>@Service</code> 的服务实现。</p>
<p><code>@Reference</code> 是 Dubbo 远程服务的依赖注入注解，需要服务提供方和消费端约定接口（interface）、版本（version）以及分组（group）信息。在当前服务消费示例中，<code>DemoService</code> 的服务版本来源于属性配置文件 <code>consumer-config.properties</code>。</p>
<p><code>@PostConstruct</code> 部分代码则说明当 <code>DemoServiceConsumerBootstrap</code> Bean 初始化时，执行十次 Dubbo 远程方法调用。</p>
<h4>运行注解驱动示例</h4>
<p>在本地启动两次 <code>DemoServiceProviderBootstrap</code>，注册中心将出现两个健康服务：</p>
<p><img src="https://img.alicdn.com/tfs/TB1s9fbzMHqK1RjSZFgXXa7JXXa-2390-122.png" alt="image-20181213123909636-4675949.png | left | 747x38"></p>
<p>再运行 <code>DemoServiceConsumerBootstrap</code>，运行结果如下：</p>
<pre><code>Service [name :demoService , port : 20880] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20881] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20880] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20880] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20881] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20881] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20880] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20880] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20881] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :demoService , port : 20881] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
</code></pre>
<p>运行无误，并且服务消费方使用了负载均衡策略，将十次 RPC 调用平均分摊到两个 Dubbo 服务提供方实例中。</p>
<h3>Spring XML 配置驱动示例</h3>
<p>Spring XML 配置驱动是传统 Spring 装配组件的编程模型。</p>
<h4>服务提供方  XML 配置驱动</h4>
<ul>
<li>定义服务提供方 XML 上下文配置文件 - <code>/META-INF/spring/dubbo-provider-context.xml</code></li>
</ul>
<pre><code class="language-xml"><span class="php"><span class="hljs-meta">&lt;?</span>xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"UTF-8"</span><span class="hljs-meta">?&gt;</span></span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans"</span>
       <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
       <span class="hljs-attr">xmlns:dubbo</span>=<span class="hljs-string">"http://dubbo.apache.org/schema/dubbo"</span>
       <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd        http://dubbo.apache.org/schema/dubbo        http://dubbo.apache.org/schema/dubbo/dubbo.xsd"</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- 提供方应用信息，用于计算依赖关系 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:application</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dubbo-provider-xml-demo"</span>/&gt;</span>

    <span class="hljs-comment">&lt;!-- 使用 Nacos 注册中心 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:registry</span> <span class="hljs-attr">address</span>=<span class="hljs-string">"nacos://127.0.0.1:8848"</span>/&gt;</span>
    <span class="hljs-comment">&lt;!-- 如果要使用自己创建的命名空间可以使用下面配置 --&gt;</span>
    <span class="hljs-comment">&lt;!-- &lt;dubbo:registry address="nacos://127.0.0.1:8848?namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932" /&gt; --&gt;</span>

    <span class="hljs-comment">&lt;!-- 用dubbo协议在随机端口暴露服务 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:protocol</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dubbo"</span> <span class="hljs-attr">port</span>=<span class="hljs-string">"-1"</span>/&gt;</span>

    <span class="hljs-comment">&lt;!-- 声明需要暴露的服务接口 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:service</span> <span class="hljs-attr">interface</span>=<span class="hljs-string">"com.alibaba.dubbo.demo.service.DemoService"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"demoService"</span> <span class="hljs-attr">version</span>=<span class="hljs-string">"2.0.0"</span>/&gt;</span>

    <span class="hljs-comment">&lt;!-- 和本地bean一样实现服务 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demoService"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"com.alibaba.dubbo.demo.service.DefaultService"</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span>
</code></pre>
<ul>
<li>实现服务提供方引导类 - <code>DemoServiceProviderXmlBootstrap</code></li>
</ul>
<pre><code class="language-xml">package com.alibaba.dubbo.demo.provider;

import com.alibaba.dubbo.demo.service.DemoService;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

/**
 * {@link DemoService} provider demo XML bootstrap
 */
public class DemoServiceProviderXmlBootstrap {

    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
        context.setConfigLocation("/META-INF/spring/dubbo-provider-context.xml");
        context.refresh();
        System.out.println("DemoService provider (XML) is starting...");
        System.in.read();
    }
}
</code></pre>
<h4>服务消费方 XML 配置驱动</h4>
<ul>
<li>定义服务消费方 XML 上下文配置文件 - <code>/META-INF/spring/dubbo-consumer-context.xml</code></li>
</ul>
<pre><code class="language-xml"><span class="php"><span class="hljs-meta">&lt;?</span>xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"UTF-8"</span><span class="hljs-meta">?&gt;</span></span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans"</span>
       <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
       <span class="hljs-attr">xmlns:dubbo</span>=<span class="hljs-string">"http://dubbo.apache.org/schema/dubbo"</span>
       <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd        http://dubbo.apache.org/schema/dubbo        http://dubbo.apache.org/schema/dubbo/dubbo.xsd"</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- 提供方应用信息，用于计算依赖关系 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:application</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dubbo-consumer-xml-demo"</span>/&gt;</span>

    <span class="hljs-comment">&lt;!-- 使用 Nacos 注册中心 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:registry</span> <span class="hljs-attr">address</span>=<span class="hljs-string">"nacos://127.0.0.1:8848"</span>/&gt;</span>
    <span class="hljs-comment">&lt;!-- 如果要使用自己创建的命名空间可以使用下面配置 --&gt;</span>
    <span class="hljs-comment">&lt;!-- &lt;dubbo:registry address="nacos://127.0.0.1:8848?namespace=5cbb70a5-xxx-xxx-xxx-d43479ae0932" /&gt; --&gt;</span>

    <span class="hljs-comment">&lt;!-- 引用服务接口 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dubbo:reference</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demoService"</span> <span class="hljs-attr">interface</span>=<span class="hljs-string">"com.alibaba.dubbo.demo.service.DemoService"</span> <span class="hljs-attr">version</span>=<span class="hljs-string">"2.0.0"</span>/&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span>
</code></pre>
<ul>
<li>实现服务消费方引导类 - <code>DemoServiceConsumerXmlBootstrap</code></li>
</ul>
<pre><code class="language-java"><span class="hljs-keyword">package</span> com.alibaba.dubbo.demo.consumer;

<span class="hljs-keyword">import</span> com.alibaba.dubbo.demo.service.DemoService;

<span class="hljs-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;

<span class="hljs-keyword">import</span> java.io.IOException;

<span class="hljs-comment">/**
 * {<span class="hljs-doctag">@link</span> DemoService} consumer demo XML bootstrap
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DemoServiceConsumerXmlBootstrap</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException </span>{
        ClassPathXmlApplicationContext context = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext();
        context.setConfigLocation(<span class="hljs-string">"/META-INF/spring/dubbo-consumer-context.xml"</span>);
        context.refresh();
        System.out.println(<span class="hljs-string">"DemoService consumer (XML) is starting..."</span>);
        DemoService demoService = context.getBean(<span class="hljs-string">"demoService"</span>, DemoService.class);
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
            System.out.println(demoService.sayName(<span class="hljs-string">"小马哥（mercyblitz）"</span>));
        }
        context.close();
    }
}
</code></pre>
<h4>运行 XML 配置驱动示例</h4>
<p>同样地，先启动两个 <code>DemoServiceProviderXmlBootstrap</code> 引导类，观察 Nacos 注册中心服务提供者变化：</p>
<p><img src="https://img.alicdn.com/tfs/TB1HCfbzMHqK1RjSZFgXXa7JXXa-2388-106.png" alt="image-20181213125527201-4676927.png | left | 747x33"></p>
<p>XML 配置驱动的服务版本为 <code>2.0.0</code>，因此注册服务无误。</p>
<p>再运行服务消费者引导类 <code>DemoServiceConsumerXmlBootstrap</code>，观察控制台输出内容：</p>
<pre><code>Service [name :null , port : 20882] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20882] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20883] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20882] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20882] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20883] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20882] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20883] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20883] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
Service [name :null , port : 20883] sayName(&quot;小马哥（mercyblitz）&quot;) : Hello,小马哥（mercyblitz）
</code></pre>
<p>结果同样运行和负载均衡正常，不过由于当前示例尚未添加属性 <code>demo.service.name</code> 的缘故，因此，“name”部分信息输出为 <code>null</code>。</p>
<p>如果您关注或喜爱 Dubbo 以及 Nacos 等开源工程，不妨为它们点 “star”，加油打气链接：</p>
<ul>
<li>Apache Dubbo：<a href="https://github.com/apache/dubbo">https://github.com/apache/dubbo</a></li>
<li>Dubbo Nacos Registry：<a href="https://github.com/apache/dubbo/tree/master/dubbo-registry/dubbo-registry-nacos">https://github.com/apache/dubbo/tree/master/dubbo-registry/dubbo-registry-nacos</a></li>
<li>Alibaba Nacos：<a href="https://github.com/alibaba/nacos">https://github.com/alibaba/nacos</a></li>
</ul>
</div></div></section><footer class="footer-container" data-reactid="139"><div class="footer-body" data-reactid="140"><img src="/img/nacos_gray.png" data-reactid="141"/><div class="cols-container" data-reactid="142"><div class="col col-12" data-reactid="143"><h3 data-reactid="144">愿景</h3><p data-reactid="145">Nacos 通过提供简单易用的动态服务发现、服务配置、服务共享与管理等服务基础设施，帮助用户在云原生时代，在私有云、混合云或者公有云等所有云环境中，更好的构建、交付、管理自己的微服务平台，更快的复用和组合业务服务，更快的交付商业创新的价值，从而为用户赢得市场。</p></div><div class="col col-6" data-reactid="146"><dl data-reactid="147"><dt data-reactid="148">文档</dt><dd data-reactid="149"><a href="/zh-cn/docs/what-is-nacos.html" target="_self" data-reactid="150">概览</a></dd><dd data-reactid="151"><a href="/zh-cn/docs/quick-start.html" target="_self" data-reactid="152">快速开始</a></dd><dd data-reactid="153"><a href="/zh-cn/docs/contributing.html" target="_self" data-reactid="154">开发者指南</a></dd></dl></div><div class="col col-6" data-reactid="155"><dl data-reactid="156"><dt data-reactid="157">资源</dt><dd data-reactid="158"><a href="/zh-cn/community/index.html" target="_self" data-reactid="159">社区</a></dd><dd data-reactid="160"><a href="https://www.aliyun.com/product/acm?source_type=nacos_pc_20181219" target="_self" data-reactid="161">云服务 ACM</a></dd><dd data-reactid="162"><a href="https://www.aliyun.com/product/edas?source_type=nacos_pc_20181219" target="_self" data-reactid="163">云服务 EDAS</a></dd><dd data-reactid="164"><a href="https://www.aliyun.com/product/ahas?source_type=nacos_pc_20190225" target="_self" data-reactid="165">云服务 AHAS</a></dd></dl></div></div><div class="copyright" data-reactid="166"><span data-reactid="167">@ 2018 The Nacos Authors | An Alibaba Middleware (Aliware) Project</span></div></div></footer></div></div>
	<script src="https://f.alicdn.com/react/15.4.1/react-with-addons.min.js"></script>
	<script src="https://f.alicdn.com/react/15.4.1/react-dom.min.js"></script>
	<script>
		window.rootPath = '';
  </script>
	<script src="/build/documentation.js"></script>
</body>
</html>